import queryString from 'query-string';
import { Base64 } from 'js-base64';

class Route {
  public query: any;
  constructor() {
    this.query = {};
  }
  setQuery(data: any) {
    this.query = data;
  }
}
class Router {
  public routes: any;
  public currentPages: Array<any>;
  // public route: Route
  public type: string;
  // 是否开启简单模式，简单模式下，参数只能是字符串
  public isSimpleUrl: boolean = true;
  public to: any;
  public from: any;
  public routerBefore: any;
  public routerAfter: any;
  public urlMode: string;
  constructor(config: any) {
    this.routes = config.routes;
    this.currentPages = [];
    // this.route = new Route();
    this.type = '';
    this.isSimpleUrl = config.isSimpleUrl;
    this.to = null;
    this.from = null;
    // #ifdef H5
    if (config.urlMode) {
      this.urlMode = config.urlMode;
    } else {
      // 默认为hash模式
      this.urlMode = 'hash';
    }
    // #endif
    console.log('路由初始化成功');
  }
  parseQuery() {}
  getPageOptions() {
    let pages = getCurrentPages();
    let currentPage = pages[pages.length - 1];
    // #ifdef MP
    // @ts-ignore
    return currentPage.options;
    // #endif
    // @ts-ignore
    return currentPage.$page.options;
  }
  getQuery() {
    let query = this.getPageOptions();
    if (Object.keys(query).length == 0) {
      return {};
    }
    if (this.isSimpleUrl) {
      return query;
    }
    if (!query.params) {
      console.error('路由参数错误，params参数不存在');
      return {};
    }

    return JSON.parse(Base64.decode(query.params));
  }
  getQueryUrl() {
    if (this.urlMode == 'hash') {
      return window.location.hash.substr(1);
    } else {
      return window.location.href;
    }
  }
  beforeEach(config: any) {
    this.routerBefore = config;
    return config;
  }
  afterEach(config: any) {
    this.routerAfter = config;
    return config;
  }
  getRouterWithName(name: string) {
    let route = null;
    for (let i in this.routes) {
      if (name == this.routes[i].name) {
        route = this.routes[i];
        break;
      }
    }
    if (route == null) {
      console.error(name + '路由不存在');
    }
    return route;
  }
  getRouterWithPath(path: string) {
    let route = null;
    for (let i in this.routes) {
      if (path == this.routes[i].path) {
        route = this.routes[i];
        break;
      }
    }
    if (route == null) {
      console.error(path + '路由不存在');
    }
    return route;
  }
  getPath(path: string, params: any = {}) {
    let d = params;
    let _str = '';
    // @ts-ignore
    if (Object.keys(d).length !== 0) {
      console.log(d);
      path = path + '?';
      if (!this.isSimpleUrl) {
        path = path + 'params=' + Base64.encodeURI(JSON.stringify(d));
      } else {
        for (let o in d) {
          if (typeof d[o] == 'object') {
            console.error(o + '：简单参数模式，参数中不能包含对象');
          } else {
            path = path + '&' + o + '=' + d[o];
          }
        }
      }
    }
    return path;
  }
  jumpFunc(config: any, type: string) {
    console.log(config);
    let arr = getCurrentPages();
    if (arr.length > 0) {
      this.from = this.getRouterWithPath('/' + arr[arr.length - 1].route);
    }
    this.type = type;
    if (type == 'back') {
      if (config >= arr.length) {
        this.to = this.routes[0];
        this.type = 'replaceAll';
        // this.route.setQuery({});
      } else {
        this.to = this.getRouterWithPath(
          '/' + arr[arr.length - 1 - config].route
        );
        this.to.params = config;
        // this.route.setQuery({});
      }
    } else {
      let router = this.getRouterWithName(config.name);
      let path = this.getPath(router.path, config.params);
      this.to = router;
      // this.route.setQuery(config.params);
      this.to.params = config.params;
      this.to.allPath = path;
    }
    this.routerBefore(this.to, this.from, this.next.bind(this));
  }
  next() {
    switch (this.type) {
      case 'back':
        uni.navigateBack({
          delta: this.to.params,
        });
        break;
      case 'push':
        console.log(this.to);
        uni.navigateTo({
          url: this.to.allPath || this.to.path,
        });
        break;
      case 'replace':
        uni.redirectTo({
          url: this.to.allPath || this.to.path,
        });
        break;
      case 'replaceAll':
        uni.reLaunch({
          url: this.to.allPath || this.to.path,
        });
        break;
      case 'switchTab':
        uni.switchTab({
          url: this.to.allPath || this.to.path,
        });
        break;
    }
    this.routerAfter(this.to, this.from);
  }
  push(config: any) {
    this.jumpFunc(config, 'push');
  }
  back(num = 1) {
    if (num < 1) {
      console.error('back参数不正确');
      return;
    }
    this.jumpFunc(num, 'back');
  }
  replace(config: any) {
    this.jumpFunc(config, 'replace');
  }
  replaceAll(config: any) {
    this.jumpFunc(config, 'replaceAll');
  }
  switchTab(config: any) {
    this.jumpFunc(config, 'switchTab');
  }
}

// @ts-ignore
let router = new Router({
  // @ts-ignore
  routes: [...ROUTER],
  urlMode: 'hash',
  isSimpleUrl: false, // 是否开启简单模式，简单模式下，参数只能是字符串
});
//全局路由前置守卫
router.beforeEach((to: any, from: any, next: any) => {
  console.log(to);
  next();
});
// 全局路由后置守卫
router.afterEach((to: any, from: any) => {
  console.log('跳转结束');
});

export default router;
